<template>
  <div class="analysis-container">
    <div class="header">
      <h2>查询日志</h2>
      <div class="time-filter">
        <span>当前模拟时间：</span>
        <el-tag type="info">{{ formattedTime }}</el-tag>
        <el-button
            type="primary"
            size="small"
            :icon="Refresh"
            style="margin-left: 10px"
            @click="reloadCurrentView"
        >
          刷新
        </el-button>
      </div>
    </div>
    <el-tabs v-model="activeTab" type="card">
      <!-- 爆款新闻分析选项卡 -->
      <el-tab-pane label="爆款新闻分析" name="hotNewsAnalysis">
        <el-card shadow="hover" class="analysis-section">
          <template #header>
            <div class="section-header">
              <h3>爆款新闻特征分析</h3>
              <el-button type="primary" size="small" @click="analyzeHotNews">
                <el-icon><Refresh /></el-icon>
                重新分析
              </el-button>
            </div>
          </template>

          <div class="hot-news-analysis">
            <!-- 饼图展示区域 -->
            <el-row :gutter="20" style="margin-bottom: 20px;">
              <el-col :span="8">
                <el-card shadow="hover">
                  <template #header>
                    <div class="card-header">
                      <span>爆款新闻TOP5</span>
                    </div>
                  </template>
                  <div ref="hotNewsPieChart" style="height: 300px;"></div>
                </el-card>
              </el-col>
              <el-col :span="8">
                <el-card shadow="hover">
                  <template #header>
                    <div class="card-header">
                      <span>爆款主题TOP5</span>
                    </div>
                  </template>
                  <div ref="hotTopicsPieChart" style="height: 300px;"></div>
                </el-card>
              </el-col>
              <el-col :span="8">
                <el-card shadow="hover">
                  <template #header>
                    <div class="card-header">
                      <span>爆款分类TOP5</span>
                    </div>
                  </template>
                  <div ref="hotCategoriesPieChart" style="height: 300px;"></div>
                </el-card>
              </el-col>
            </el-row>

            <div class="hot-news-examples">
              <h4>近期爆款新闻示例：</h4>
              <el-table :data="hot_news" style="width: 100%" border stripe>
                <el-table-column prop="TITLE" label="标题"/>
                <el-table-column prop="CATEGORY" label="分类"/>
                <el-table-column prop="TOPIC" label="主题"/>
                <el-table-column prop="RATE" label="总阅读时长(ms)" width="150" align="center" />
                <el-table-column label="操作" align="center" fixed="right">
                  <template #default="{row}">
                    <el-button type="text" size="small" @click="viewNewsDetail(row)">查看详情</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>

            <el-dialog v-model="newsDetailVisible" title="新闻详情" width="70%">
              <el-descriptions :column="1" border>
                <el-descriptions-item label="新闻内容">
                  <div class="news-content">{{ current_news_content }}</div>
                </el-descriptions-item>
              </el-descriptions>
              <template #footer>
                <el-button @click="newsDetailVisible = false">关闭</el-button>
              </template>
            </el-dialog>

          </div>
        </el-card>
      </el-tab-pane>

      <!-- 实时新闻推荐选项卡 -->
      <el-tab-pane label="实时新闻推荐" name="realTimeRecommend">
        <el-card shadow="hover" class="recommend-section">
          <template #header>
            <div class="section-header">
              <h3>个性化新闻推荐</h3>
              <div class="recommend-actions">
                <el-input
                    v-model="userId"
                    placeholder="输入用户ID"
                    style="width: 200px; margin-right: 10px;"
                    @keyup.enter="fetchRecommendations"
                />
                <el-button type="primary" @click="fetchRecommendations">
                  <el-icon><Search /></el-icon>
                  查询
                </el-button>
              </div>
            </div>
          </template>

          <div class="real-time-recommendations">
            <div v-if="recommendedNews.length > 0">
              <h4>为您推荐的新闻：</h4>
              <el-row :gutter="20">
                <el-col :span="8" v-for="(news, index) in recommendedNews" :key="index" style="margin-bottom: 20px;">
                  <el-card shadow="hover" :body-style="{ padding: '0px' }">
                    <div class="news-card">
                      <el-image class="news-image">
                        <template #error>
                          <div class="image-slot">
                            <el-icon><Picture/></el-icon>
                          </div>
                        </template>
                      </el-image>
                      <div class="news-content">
                        <h4 class="news-title">{{ news.HEADLINE }}({{news.NEWS_ID}})</h4>
                        <div class="news-meta">
                          <span class="news-category">新闻分类：{{ news.CATEGORY }}</span>
                          <span class="news-topic">新闻主题：{{ news.TOPIC }}</span>
                        </div>
                        <div class="news-actions">
                          <el-button type="primary" size="small" @click="viewNewsDetail(news)">查看详情</el-button>
                        </div>
                      </div>
                    </div>
                  </el-card>
                </el-col>
              </el-row>
            </div>

            <div v-else class="empty-recommendation">
              <el-empty description="请输入用户ID并点击查询获取推荐新闻" />
            </div>

            <el-dialog v-model="newsDetailVisible" title="新闻详情" width="70%">
              <el-descriptions :column="1" border>
                <el-descriptions-item label="新闻内容">
                  <div class="news-content">{{ current_news_content }}</div>
                </el-descriptions-item>
              </el-descriptions>
              <template #footer>
                <el-button @click="newsDetailVisible = false">关闭</el-button>
              </template>
            </el-dialog>
          </div>
        </el-card>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script setup lang="ts">
import {ref, onMounted, onUnmounted, nextTick} from 'vue'
import { Refresh,Search,Picture  } from '@element-plus/icons-vue'
import * as echarts from 'echarts'
import { useSimulationStore } from '@/store/simulation'
import { storeToRefs } from "pinia"
import {ElMessage} from "element-plus";
import axios from "axios";

const simulationStore = useSimulationStore()

// 从store获取模拟时间
const { formattedTime } = storeToRefs(simulationStore)

const activeTab = ref('hotNewsAnalysis')


// 爆款新闻分析相关
const hot_news = ref<any[]>([])
// 图表引用
const hotNewsPieChart = ref<HTMLElement | null>(null)
const hotTopicsPieChart = ref<HTMLElement | null>(null)
const hotCategoriesPieChart = ref<HTMLElement | null>(null)
const hotNewsList = ref<any[]>([])
const hotTopicsList = ref<any[]>([])
const hotCategoriesList = ref<any[]>([])

// 实时推荐相关
const userId = ref('')
const recommendedNews = ref([])
const loading = ref(false)
const newsDetailVisible = ref(false)
const current_news_content = ref('')

// 分析爆款新闻
const analyzeHotNews = () => {
  fetchHotNews()
}

// 获取爆款新闻数据
const fetchHotNews = async () => {
  try {
    const response = await axios.get('http://localhost:5000/query_hot_news')
    if (!response.data.data) {
      ElMessage.warning("未查询到相关内容！")
      return
    }
    // 分类处理数据
    hotNewsList.value = response.data.data
        .filter((item: any) => item.type === 1)
        .sort((a: any, b: any) => b.rate - a.rate)
        .slice(0, 5)

    hotTopicsList.value = response.data.data
        .filter((item: any) => item.type === 2)
        .sort((a: any, b: any) => b.rate - a.rate)
        .slice(0, 5)

    hotCategoriesList.value = response.data.data
        .filter((item: any) => item.type === 3)
        .sort((a: any, b: any) => b.rate - a.rate)
        .slice(0, 5)

    // 更新图表
    updatePieCharts()

    // 获取hotNewsList中所有新闻的详细信息
    const newsDetailsPromises = hotNewsList.value.map(item =>
        axios.get('http://localhost:5000/get_news_by_id', {
          params: { news_id: item.name }
        })
    )

    const newsDetailsResponses = await Promise.all(newsDetailsPromises)

    // 处理新闻详情数据
    hot_news.value = newsDetailsResponses
        .filter(response => response.data.status === 'success')
        .map(response => {
          const news = response.data.data
          return {
            NEWS_ID: news.NEWS_ID,
            TITLE: news.HEADLINE,
            CATEGORY: news.CATEGORY,
            TOPIC: news.TOPIC,
            RATE: hotNewsList.value.find(item => item.name === news.NEWS_ID)?.rate || 0,
            CONTENT: news.NEWS_BODY
          }
        })
  } catch (error) {
    console.error('获取爆款新闻失败:', error)
    ElMessage.error('获取爆款新闻失败')
  }
}

// 更新饼图
const updatePieCharts = () => {
  nextTick(() => {
    // 爆款新闻饼图
    if (hotNewsPieChart.value) {
      const newsChart = echarts.init(hotNewsPieChart.value)
      const newsOption = getPieChartOption(
          '爆款新闻TOP5',
          hotNewsList.value.map(item => item.name),
          hotNewsList.value.map(item => item.rate)
      )
      newsChart.setOption(newsOption)
    }

    // 爆款主题饼图
    if (hotTopicsPieChart.value) {
      const topicsChart = echarts.init(hotTopicsPieChart.value)
      const topicsOption = getPieChartOption(
          '爆款主题TOP5',
          hotTopicsList.value.map(item => item.name),
          hotTopicsList.value.map(item => item.rate)
      )
      topicsChart.setOption(topicsOption)
    }

    // 爆款分类饼图
    if (hotCategoriesPieChart.value) {
      const categoriesChart = echarts.init(hotCategoriesPieChart.value)
      const categoriesOption = getPieChartOption(
          '爆款分类TOP5',
          hotCategoriesList.value.map(item => item.name),
          hotCategoriesList.value.map(item => item.rate)
      )
      categoriesChart.setOption(categoriesOption)
    }
  })
}

// 获取饼图配置
const getPieChartOption = (title: string, names: string[], values: number[]) => {
  return {
    title: {
      text: title,
      left: 'center'
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      data: names
    },
    series: [
      {
        name: '阅读时长',
        type: 'pie',
        radius: ['50%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '18',
            fontWeight: 'bold',
            formatter: '{b}\n{d}%'
          }
        },
        labelLine: {
          show: false
        },
        data: names.map((name, index) => ({
          value: values[index],
          name: name
        }))
      }
    ]
  }
}

// 窗口大小变化时重绘图表
const handleResize = () => {
  if (hotNewsPieChart.value) {
    const chart = echarts.getInstanceByDom(hotNewsPieChart.value)
    chart?.resize()
  }
  if (hotTopicsPieChart.value) {
    const chart = echarts.getInstanceByDom(hotTopicsPieChart.value)
    chart?.resize()
  }
  if (hotCategoriesPieChart.value) {
    const chart = echarts.getInstanceByDom(hotCategoriesPieChart.value)
    chart?.resize()
  }
}
// 获取推荐新闻
const fetchRecommendations = async () => {
  if (!userId.value) {
    ElMessage.error("请输入用户ID")
    return
  }
  loading.value = true
  recommendedNews.value = []
  try {
    // 1. 获取推荐新闻ID列表
    const recommendResponse = await axios.get(`http://localhost:44443/recommend?userId=U${userId.value}`)

    // 处理推荐结果
    if (recommendResponse.data === '-1') {
      ElMessage.error("没有该用户的曝光日志，无法推荐")
      return
    }
    if (recommendResponse.data === '-2') {
      ElMessage.error('推荐模型尚未训练完成')
      return
    }

    const newsIds = recommendResponse.data.split('\n').filter((id:any) => id.startsWith('N'))
    if (newsIds.length === 0) {
      ElMessage.error('没有找到推荐新闻')
      return
    }

    // 2. 获取每个新闻的详细信息
    const newsDetailsPromises = newsIds.map((id:any) =>
        axios.get('/get_news_by_id', {params: {news_id: id}})
    )

    const newsDetailsResponses = await Promise.all(newsDetailsPromises)

    // 3. 处理新闻详情数据
    recommendedNews.value = newsDetailsResponses
        .filter(response => response.data.status === 'success')
        .map(response => {
          const news = response.data.data
          return {
            NEWS_ID: news.NEWS_ID,
            HEADLINE: news.HEADLINE,
            TOPIC: news.TOPIC,
            CATEGORY: news.CATEGORY,
            NEWS_BODY: news.NEWS_BODY
          }
        })

  } catch (error) {
    console.error('获取推荐新闻失败:', error)
    ElMessage.error('获取推荐新闻失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 查看新闻详情
const viewNewsDetail = (news: any) => {
  newsDetailVisible.value = true
  console.log('查看新闻详情:', news)
  current_news_content.value = news.NEWS_BODY
}



const reloadCurrentView = () => {
  userId.value = ''
  activeTab.value = 'hotNewsAnalysis'
  fetchHotNews()
}

onMounted(() => {
  fetchHotNews()
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
})
</script>

<style scoped>
.analysis-container {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.time-filter {
  display: flex;
  align-items: center;
}


.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.analysis-section {
  margin-bottom: 20px;
}

.card-header {
  font-weight: bold;
  font-size: 16px;
}

.hot-news-tips h4 {
  margin-bottom: 10px;
  color: #333;
}

.hot-news-examples {
  margin-top: 20px;
}

.hot-news-examples h4 {
  margin-bottom: 15px;
  color: #333;
}

.recommend-actions {
  display: flex;
  align-items: center;
}

.news-card {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.news-image {
  margin-top:10px;
  padding: 0 5px;
  width: 100%;
  height: 250px
}

.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: var(--el-fill-color-light);
  color: var(--el-text-color-secondary);
  font-size: 30px;
}

.news-content {
  padding: 15px;
}

.news-title {
  font-size: 16px;
  margin-bottom: 10px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  height: 48px;
}

.news-meta {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
  color: #666;
  font-size: 12px;
}

.news-stats span {
  display: flex;
  align-items: center;
}

.news-actions {
  display: flex;
  justify-content: space-between;
}

.empty-recommendation {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 300px;
  border: 1px dashed #ddd;
  border-radius: 4px;
}

.el-tabs {
  background: #fff;
  padding: 0 20px;
  border-radius: 4px;
}

.el-tab-pane {
  padding: 20px 0;
}
</style>